import {createAlova} from "alova";
import {axiosRequestAdapter} from "@alova/adapter-axios";
import VueHook from "alova/vue-demi";
import {message} from "ant-design-vue";
import {isDev} from "@/utils";
import router from "@/router/router";
import {STORAGE} from "@/utils/config";
import {navPath} from "@/router/config";
import _ from "lodash";

interface ResponseData {
    msg: "success" | "fail";
    code: 200 | 500 | 401;
    data: any;
}

interface CodeItem {
    desc: string;
    code: number;
    nav?: string;
}

const CODE: CodeItem[] = [
    {
        desc: "token已过期,请重新登录。",
        code: 401,
        nav: navPath.login,
    },
    {
        desc: "token无效",
        code: 403,
        nav: navPath.login,
    },
    {
        desc: "当前接口未授权",
        code: 402,
    },
];

export const http = createAlova({
    baseURL: "",
    timeout: 10000,
    statesHook: VueHook,
    cacheFor: {
        GET: 0,
    },
    requestAdapter: axiosRequestAdapter(),
    beforeRequest(method) {
        method.config.responseType = "json";
        const auth = sessionStorage.getItem(STORAGE.AUTHORIZATION) || "";
        method.config.headers.Authorization = auth ? "Bearer" + ` ${auth}` : auth;
    },
    cacheLogger: isDev,
    // 使用数组的两个项，分别指定请求成功的拦截器和请求失败的拦截器
    responded: {
        // 第二个参数为当前请求的method实例，你可以用它同步请求前后的配置信息
        onSuccess: async (response: any) => {
            console.log("response", response);
            const data: ResponseData = response.data;
            if (data.code !== 200) {
                return Promise.reject(data);
            }
            return Promise.resolve(data.data);
        },
        onError: err => {
            const {code, msg} = err.response.data;
            const item: any = _.find(CODE, {code}) || {};
            if (!_.isEmpty(item)) {
                message.destroy();
                message.error(item.desc);
                if (item.nav) {
                    const {pathname, search} = window.location;
                    if (pathname !== navPath.login) {
                        sessionStorage.clear();
                        router.push({path: navPath.login, query: {redirect: pathname + search}});
                    }
                }
            } else {
                message.error(`请求失败:${msg} code: ${code}`);
                return Promise.reject(err);
            }
        },
    },
});

export const GetRequest = (path, data) => http.Get(path, {params: data});
export const PostRequest = (path, data) => http.Post(path, data);
export const PutRequest = (path, data) => http.Put(path, data);
export const DeleteRequest = (path, data) => http.Delete(path, data);
export const UploadRequest = (path, data) => http.Post(path, data, {headers: {"Content-Type": "multipart/form-data"}});
